<script>
import userManger from "@/api/userManger";
import roleManger from "@/api/roleManger";
  export default {
    data(){
      let checkPassword= (rule, value, callback) => {
        console.log(this.form.password)
        if(this.form.password!=value){
          new callback(new Error("密码不一致"))
        }else{
          callback() //通过
        }
      }
      let checkPhone=(rule, value, callback) => {
        let regPhone=/^1(3|4|5|6|7|8|9)\d{9}$/
        if(!regPhone.test(value)){
          callback(new Error("请正确输入手机格式"))
        }else{
          callback()
        }
      }
      let checkEmail=(rule, value, callback) => {
        let regEmail=/^\w{3,18}@\w{2,10}\.[a-z]{2,4}$/
        if(!regEmail.test(value)){
          callback(new Error("请合法输入邮箱格式"))
        }else{
          callback()
        }
      }
      return{
        searchModel:{
          username:"",
          phone:"",
          pageSize:5,  //默认每页显示的数量
          currentPage:1 //默认当前页数
        },
        total:0,
        tableData:[],
        form:{},
        dialogFormVisible:false,
        formLabelWidth:"100px",
        title:"",
        options:[],
        rules:{
          username:[
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入用户密码', trigger: 'blur' },
            { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
          ],
          confirmPassWord:[
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { validator: checkPassword, trigger: 'blur' }
          ],
          phoneNumber:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkPhone, trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, trigger: 'blur' }
          ]
        },
        ids:[]
      }
    },
    methods:{
      tableRowClassName({row, rowIndex}) {
        if (rowIndex === 1) {
          return 'warning-row';
        } else if (rowIndex === 3) {
          return 'success-row';
        }
        return '';
      },
      //每页显示的条数
      handleSizeChange(size){
        this.searchModel.pageSize=size;
        this.getTableData();
      },
      //当前页数
      handleCurrentChange(page){
       this.searchModel.currentPage=page;
        this.getTableData();
      },
      //获取所有用户数据
      getTableData(){
        userManger.getTableDataApi(this.searchModel).then(res=>{
            //将后台数据赋值给vue数据源
          this.tableData=res.data.users;
          this.total=res.data.total;
          console.log("获取的用户数据:", this.tableData);
          // 检查每个用户的status字段
          this.tableData.forEach(user => {
            console.log(`用户 ${user.username}: status=${user.status}, roleName=${user.roleName}`);
          });
        })
      },
      //修改用户状态
      updateStatus(row){
          console.log("更新用户状态:", row);
          console.log("用户ID:", row.userId, "新状态:", row.status);
          userManger.updateStatusApi(row).then(res=>{
              this.$message.success(res.message)
              console.log("状态更新成功");
          }).catch(error => {
              console.error("状态更新失败:", error);
              this.$message.error("状态更新失败");
          })
      },
      //重置
      reset(){
        this.searchModel.username=""
        this.searchModel.phone=""
        this.getTableData()
      },
      //新增/编辑对话框
      updateOradd(row){
        if(row==null){//新增
            this.title="新增用户"
            this.form = {}
        }else{//编辑
            this.title="用户编辑"
            // 复制行数据，确保roleId字段正确传递
            this.form = {
              userId: row.userId,
              username: row.username,
              email: row.email,
              phoneNumber: row.phoneNumber,
              status: row.status !== null && row.status !== undefined ? row.status : 1,
              roleId: row.roleId || null
            }
            console.log("编辑用户form数据:", this.form)
        }
        //弹出对话框
        this.dialogFormVisible=true
      },
      //获取所有角色
      getAllRole(){
        roleManger.getAllRoleApi().then(res=>{
           this.options=res.data
        })
      },
      //清空表单
      clearForm(){
        this.form={}//清空表单
        //清空表单验证结果
        this.$refs.ruleForm.clearValidate()
      },
      //编辑/新增对话框确定
      updateAndSave(){
        this.$refs.ruleForm.validate((valid)=>{
          if(valid){//校验成功
              userManger.updateAndSaveApi(this.form).then(res=>{
                if(res.code==200){
                  this.$message.success(res.message)
                  this.getTableData()
                  //关闭对话框
                  this.dialogFormVisible=false
                }else{
                  this.$message.error(res.message)
                }
              })
          }else{
            this.$message.error("请仔细填写内容")
            return false
          }
        })
      },
      //删除
      delData(row){
        this.$confirm(`此操作将永久删除${row.username}, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //删除业务
          userManger.delDataApi(row.userId).then(res=>{
            this.$message.success(res.message)
            this.getTableData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //多选框选择
      handleSelectionChange(row){
        //获取每个对象中的userId
        //使用vue提供的map()进行遍历
        this.ids= row.map(v=>v.userId)
      },
      //批量删除
      delDataByIds(){
        this.$confirm(`此操作将永久删除, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //批量删除业务
          userManger.delDataByIdsApi(this.ids).then(res=>{
            this.$message.success(res.message)
            this.getTableData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //导出
      exportOut(){
        window.open("http://localhost:8998/user/exportOut")//重新打开一个页面
        //window.location.href="https://www.baidu.com/" //在原来的页面上打开
      },
      //上传成功后的回调
      uploadMessage(res){
        this.$message.success(res.message)
      }
    },
    //先执行该方法然后在渲染页面
    created() {
      this.getTableData()
      this.getAllRole()
    }
  }
</script>

<template>
  <div>
    <!--搜索区-->
    <el-card>
      <el-row style="margin-bottom: 20px">
        <el-input style="width: 200px;margin-right: 15px"  v-model="searchModel.username" placeholder="请输入用户名称" suffix-icon="el-icon-user-solid"></el-input>
        <el-input style="width: 200px;margin-right: 15px"  v-model="searchModel.phone" placeholder="请输入用户电话" suffix-icon="el-icon-phone"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getTableData">查询</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="reset">重置</el-button>
      </el-row>
      <el-row>
        <el-button type="primary" icon="el-icon-plus" @click="updateOradd(null)">新增</el-button>
        <el-button type="danger" icon="el-icon-delete-solid"  @click="delDataByIds" >批量删除</el-button>
          <el-upload
            style="display: inline-block;margin: 0 15px"
            class="upload-demo"
            :show-file-list=false
            :on-success="uploadMessage"
            action="http://localhost:8998/user/importData"
            >
            <el-button type="primary" icon="el-icon-download">导入</el-button>
          </el-upload>
        <el-button type="primary" icon="el-icon-upload" @click="exportOut">导出</el-button>
      </el-row>
    </el-card>

  <!-- 结果列表-->
    <el-card>
      <el-table border  @selection-change="handleSelectionChange" :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
        <el-table-column type="selection"   width="55">
        </el-table-column>
        <el-table-column prop="userId" label="ID"  width="60">
        </el-table-column>
        <el-table-column prop="username" label="名称"  width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"  width="180">
        </el-table-column>
        <el-table-column prop="phoneNumber" label="电话"  width="150">
        </el-table-column>
        <el-table-column prop="status" label="状态"  width="80">
          <template v-slot="s">
            <el-tag v-if="s.row.status===1"  type="success">正常</el-tag>
            <el-tag v-if="s.row.status===0" type="danger">禁用</el-tag>
            <el-tag v-if="s.row.status===null || s.row.status===undefined" type="warning">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column  label="启用"  width="80">
          <template v-slot="s">
            <el-switch
              v-model="s.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc"
              @change="updateStatus(s.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column  label="角色"  width="100">
          <template v-slot="s">
            <el-tag v-if="s.row.roleName=='admin'" type="danger">管理员</el-tag>
            <el-tag v-if="s.row.roleName=='teacher'" type="success">教师</el-tag>
            <el-tag v-if="s.row.roleName=='student'" type="primary">学生</el-tag>
            <el-tag v-if="!s.row.roleName" type="info">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template v-slot="s">
            <el-button type="warning" icon="el-icon-edit" @click="updateOradd(s.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delData(s.row)">删除</el-button>
          </template>

        </el-table-column>
      </el-table>
    </el-card>

  <!--分页模块-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.searchModel.currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.total">
    </el-pagination>

  <!--编辑/新增对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible"  @close="clearForm">
      <el-form :model="form" :rules="rules" ref="ruleForm" >
        <el-form-item label="用户名称" prop="username" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="title=='新增用户'"  prop="password"  label="用户密码" :label-width="formLabelWidth">
          <el-input type="password"  v-model="form.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item  v-if="title=='新增用户'"  prop="confirmPassWord"  label="确认密码" :label-width="formLabelWidth">
          <el-input type="password" v-model="form.confirmPassWord" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户电话" prop="phoneNumber"  :label-width="formLabelWidth">
          <el-input v-model="form.phoneNumber"    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email"   :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-select v-model="form.roleId" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.roleId"
              :label="item.name"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAndSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
